package org.eclipse.soc.scripting.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

/**
 * A helper class that is used in plug-in initialization code
 * 
 * @author ant
 * 
 */
public class Util {

	public static URL getInitializationData(IConfigurationElement config,
			String scriptFileName) {
		
		Bundle bundle = Platform.getBundle(config.getContributor().getName());
		
		Enumeration<?> entries = bundle.findEntries("/", scriptFileName, false);
		
		URL entry = null; // if the script wasn't found, then returns null
		if (entries != null && entries.hasMoreElements()) {
			entry = (URL) entries.nextElement();
		}

		return entry;
	}

	public static String getScriptContents(URL script) {
		if (script == null)
			return "No Script!";
		try {
			URLConnection connection = script.openConnection();
			InputStream in = connection.getInputStream();
			
			try {
				byte[] buffer = new byte[10240];
				int offset = 0;
		        int numRead = 0;
		        while (offset < buffer.length
		               && (numRead=in.read(buffer, offset, buffer.length-offset)) >= 0) {
		            offset += numRead;
		        }

				return new String(buffer, 0, offset);
			} finally {
				in.close();
			}
		} catch (IOException e) {
			return "error";
		}
	}

}
